import CocosTileHelper from "../Common/CocosHelper";
import { CUSTOM_EVENT_NAME } from "../Common/Constant";
import { GameData } from "../Common/GameData";
import LanguagetileTile from "../Common/Language";
import { forMattedMoney } from "../Common/ProjectConfig";
import getEventEmiter from "../Libraries/EventEmitter";
import GameSceneController from "../Scenes/GameSceneController";
import UIToast3 from "./UIToast3";

const {ccclass, property} = cc._decorator;

@ccclass
export default class TopAreaTs extends cc.Component {
    static I:TopAreaTs
    @property(cc.Label)
    label_coin: cc.Label = null;

    @property(cc.Label)
    label_money: cc.Label = null;

    @property(cc.Label)
    label_level: cc.Label = null;

    @property(cc.Label)
    level_title: cc.Label = null;

    @property(cc.Node)
    redbagDisLayout: cc.Node = null;
    @property(cc.Node)
    coinDisLayout: cc.Node = null;
    @property(cc.Node)
    redbagSp: cc.Node = null;
    @property(cc.Node)
    coinSp: cc.Node = null;

    onLoad () {
        TopAreaTs.I = this;
        this.init();
    }

    protected start(): void {
        
    }
    init(){
        this.addCoin(0)
        this.addRedBag(0);
        this.level_title.string = LanguagetileTile.getWord("Level").toUpperCase()
        
        getEventEmiter().on(CUSTOM_EVENT_NAME.onCoinChange, this.addCoin, this)
        getEventEmiter().on(CUSTOM_EVENT_NAME.onMoneyChange, this.addRedBag, this)
        // getEventEmiter().on(CUSTOM_EVENT_NAME.addLevel, this.addLevel, this)
    }

    setLevel(){
        this.label_level.string = GameData.LevelData.passNum + "";
    }

    async addCoin(addNum) {
        if (addNum > 0 && this.coinDisLayout) {
            await CocosTileHelper.sleepSync(1.5);
            UIToast3.popUp({type:1,num:addNum},this.coinDisLayout.convertToWorldSpaceAR(cc.Vec3.ZERO),GameSceneController.I.node);
        }
        if (this.label_coin && GameData.AccountData) {
            this.label_coin.string =  GameData.AccountData.cointotal + "";
        }
    }

    getCoinFlyTarget(){
        return this.coinDisLayout
    }

    getRedbagFlyTarget(){
        return this.redbagDisLayout
    }

    async addRedBag(addNum,playAni=true) {
        if (addNum > 0 && this.redbagDisLayout&&playAni) {
            await CocosTileHelper.sleepSync(1.5);
            UIToast3.popUp({type:2,num:addNum},this.redbagDisLayout.convertToWorldSpaceAR(cc.Vec3.ZERO),GameSceneController.I.node);
        }

        if (this.label_money && GameData.AccountData) {
            this.label_money.string = LanguagetileTile.MoneyChar + forMattedMoney(GameData.AccountData.moneytotal) + "";
        }
    }

    protected onDestroy(): void {
        getEventEmiter().off(CUSTOM_EVENT_NAME.onCoinChange, this.addCoin, this)
        getEventEmiter().off(CUSTOM_EVENT_NAME.onMoneyChange, this.addRedBag, this)
    }
}
